import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgxDatatableModule } from '@swimlane/ngx-datatable';
import { CustomerGood, CustomerGoodFilter, CustomerGoodService } from './customer-good.service';
import { PagedResultDto } from '@abp/ng.core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { CustomerGoodCreateComponent } from './customer-good-create.component';
import { CustomerGoodViewComponent } from './customer-good-view.component';

@Component({
  selector: 'app-customer-good',
  templateUrl: './customer-good.component.html',
  styleUrls: ['./customer-good.component.scss'],
  standalone: true,
  imports: [CommonModule, FormsModule, NgxDatatableModule]
})
export class CustomerGoodComponent implements OnInit {
  goods: CustomerGood[] = [];
  totalCount = 0;
  pageSize = 10;
  pageNumber = 0;
  sorting = 'creationTime DESC';
  selected = [];
  private isSearching = false;
  
  filter: CustomerGoodFilter = {};

  constructor(
    private customerGoodService: CustomerGoodService,
    private modalService: NgbModal
  ) {}

  ngOnInit() {
    this.loadData();
  }

  loadData() {
    // 根据服务器返回的错误信息，我们必须为那些被错误地标记为"必填"的字段提供一个值。
    // 我们将为用户未填写的必填字段发送一个空字符串 ''，以通过后端的验证。
    const filterToSend = {
      // 后端标记为必填的字段
      purchaseOrderNo: this.filter.purchaseOrderNo || '',
      customerOrderNo: this.filter.customerOrderNo || '',
      carNo: this.filter.carNo || '',
      driverName: this.filter.driverName || '',
      driverPhone: this.filter.driverPhone || '',
      status: this.filter.status || '',
      // 后端未标记为必填的字段，可以为 null - 根据上次错误，此字段也为必填
      expectedArrivalDateFrom: this.filter.expectedArrivalDateFrom
        ? new Date(this.filter.expectedArrivalDateFrom).toISOString()
        : null,
      expectedArrivalDateTo: this.filter.expectedArrivalDateTo
        ? (() => {
            const toDate = new Date(this.filter.expectedArrivalDateTo);
            toDate.setUTCHours(23, 59, 59, 999);
            return toDate.toISOString();
          })()
        : null,
    };

    const requestData = {
      skipCount: this.pageNumber * this.pageSize,
      maxResultCount: this.pageSize,
      sorting: this.sorting,
    };

    const request = this.isSearching
      ? this.customerGoodService.getListByConditions({ ...filterToSend, ...requestData })
      : this.customerGoodService.getList(requestData);

    request.subscribe((result: PagedResultDto<CustomerGood>) => {
      this.goods = result.items;
      this.totalCount = result.totalCount;
    });
  }

  search() {
    this.pageNumber = 0;
    this.isSearching = true;
    this.loadData();
  }

  reset() {
    this.filter = {};
    this.isSearching = false;
    this.pageNumber = 0;
    this.loadData();
  }

  create() {
    const modalRef = this.modalService.open(CustomerGoodCreateComponent, { size: 'xl', centered: true });
    modalRef.result.then((result) => {
      if (result) {
        this.loadData();
      }
    });
  }

  viewDetails() {
    if (this.selected.length > 0) {
      const modalRef = this.modalService.open(CustomerGoodViewComponent, { size: 'xl', centered: true });
      modalRef.componentInstance.id = this.selected[0].id;
    }
  }

  onSort(event) {
    const sort = event.sorts[0];
    this.sorting = `${sort.prop} ${sort.dir}`;
    this.loadData();
  }

  onPage(event: { offset: number; pageSize: number }) {
    this.pageNumber = event.offset;
    this.pageSize = event.pageSize;
    this.loadData();
  }
      
  onSelect({ selected }) {
    this.selected = [...selected];
  }

  getStatusText(status: string): string {
    if (status === 'Yes' || status === '已完成') {
      return '已完成';
    } else if (status === 'No' || status === '计划中') {
      return '计划中';
    } else {
      return '初始';
    }
  }
} 